package com.leetcode.easy;

/**
 * @Classname Solution
 * @Description TODO
 * @Date 2020/8/21 16:12
 * @Created by zfl
 */
public class SolutionCountAndSay {
    /*
    *@Description count统计每个数有多少个看，str.charAt()用来统计该数
    *@param [n]
    *@return java.lang.String
    */
    public String countAndSayOne(int n) {
        String s = "";
        int p1 = 0;
        int cur = 1;
        if ( n == 1 )
            return "1";
        String str = countAndSayOne(n - 1);
        for ( cur = 1; cur < str.length(); cur++ ) {
            if ( str.charAt(p1) != str.charAt(cur) ) {
                int count = cur - p1;
                s = s + count + ""+str.charAt(p1);
                p1 = cur;
            }
        }
        if ( p1 != cur ) {
            int count = cur - p1;
            s = s + count +""+ str.charAt(p1);
        }
        return s;
    }
    /*
    *@Description
    *@param [n]
    *@return java.lang.String
    * 执行用时：2 ms, 在所有 Java 提交中击败了68.54%的用户
    * 内存消耗：36.9 MB, 在所有 Java 提交中击败了82.46%的用户
    */
    public String countAndSayTwo(int n) {
        StringBuilder s = new StringBuilder();
        int p1 = 0;
        int cur = 1;
        if ( n == 1 )
            return "1";
        String str = countAndSayTwo(n - 1);
        for ( cur = 1; cur < str.length(); cur++ ) {
            // 如果碰到当前字符与前面紧邻的字符不等则更新此次结果
            if ( str.charAt(p1) != str.charAt(cur) ) {
                int count = cur - p1;
                s.append(count).append(str.charAt(p1));
                p1 = cur;
            }
        }
        // 防止最后一段数相等，如果不等说明p1到cur-1这段字符串是相等的
        if ( p1 != cur ){
            int count = cur - p1;
            s.append(count).append(str.charAt(p1));
        }
        return s.toString();
    }

}
